package it.duecaffe.claysoftware.interventi.client.view;

import it.duecaffe.claysoftware.interventi.client.handler.LoginEvent;
import it.duecaffe.claysoftware.interventi.client.handler.Utils;
import it.duecaffe.claysoftware.interventi.client.images.ClayResources;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DecoratedPopupPanel;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.InlineLabel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * View per la gestione della login con visualizzazione
 * dialogBox per inserimento utente e password
 * @author Alex
 *
 */
public class LoginView extends DialogBox {

	private Label serverResponseLabel;
	
	/**
	 * Costruttore
	 */
	public LoginView() {
		init();
	}

	private void init() {

		ClayResources IMAGES = GWT.create(ClayResources.class);

		// Create the popup dialog box
		ensureDebugId("cwDialogBox");
		setText("Autenticazione");
		setAnimationEnabled(true);
		setSize("300", "300");
		setGlassEnabled(true);
		setModal(true);

		// Create a table to layout the content
		VerticalPanel dialogContents = new VerticalPanel();
		dialogContents.setSpacing(4);
		
		// Logo clay
	    Image image = new Image(IMAGES.logo_login());
	    dialogContents.add(image);
	    dialogContents.setCellHorizontalAlignment(image, HasHorizontalAlignment.ALIGN_CENTER);

	    HorizontalPanel userAndLabel = new HorizontalPanel();
        InlineLabel labelUser = new InlineLabel("Nome utente:");
        
		// Textbox user id
		final TextBox userId = new TextBox();
		userId.setWidth("200");
		userId.ensureDebugId("cwBasicText-userId");
		userId.setFocus(true);
		userId.selectAll();
		
		userAndLabel.add(labelUser);
		userAndLabel.setCellWidth(labelUser,"100");
		userAndLabel.add(userId);
		
		HorizontalPanel pwdAndLabel = new HorizontalPanel();
        InlineLabel labelPwd = new InlineLabel("Password:");
        labelPwd.setWidth("300");
        
		final PasswordTextBox pwd = new PasswordTextBox();
		pwd.setWidth("200");
		pwd.ensureDebugId("cwBasicText-password");
		
		pwdAndLabel.add(labelPwd);
		pwdAndLabel.setCellWidth(labelPwd,"100");
		pwdAndLabel.add(pwd);
		
		dialogContents.add(new HTML("<br>"));
		
		dialogContents.add(userAndLabel);
		dialogContents.add(pwdAndLabel);

		Button clearButton = new Button("Cancella");
		// We can set the id of a widget by accessing its Element
		clearButton.getElement().setId("clearButton");
		// Add a handler to close the DialogBox
		clearButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				userId.setValue("");
				userId.setFocus(true);
				pwd.setValue("");
				pwd.setEnabled(false);
			}
		});

		final Button loginButton = new Button("Login");
		loginButton.addStyleName("sendButton");

		HorizontalPanel hPanel = new HorizontalPanel();
		hPanel.setWidth("100%");
		hPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
		hPanel.setSpacing(5);
		
		hPanel.add(clearButton);
		hPanel.add(loginButton);
		
		dialogContents.add(new HTML("<br>"));
		dialogContents.add(hPanel);
		
		// Gestione errore
		serverResponseLabel = new Label();
		serverResponseLabel.setWidth("100%");
		serverResponseLabel.setStyleName("labelRed");
		dialogContents.add(serverResponseLabel);

		setWidget(dialogContents);

		// Add the nameField and sendButton to the RootPanel
		// Use RootPanel.get() to get the entire body element
		RootPanel.get("dialogBoxAut").add(this);


		// Create a handler for the sendButton and nameField
		class MyHandler implements ClickHandler, KeyUpHandler {
			/**
			 * Fired when the user clicks on the sendButton.
			 */
			public void onClick(ClickEvent event) {
				validateLogin();
			}

			/**
			 * Fired when the user types in the nameField.
			 */
			public void onKeyUp(KeyUpEvent event) {
				if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
					validateLogin();
				}
				if (userId.getValue() != null) {
					pwd.setEnabled(true);
				} else {
					pwd.setEnabled(false);
				}
			}

			/**
			 * Send the name from the nameField to the server and wait for a response.
			 */
			private void validateLogin() {
				// First, we validate the input.
				String username = userId.getValue();
				String password = pwd.getValue();
				if (username == null || username.trim() == "" || 
						password == null || password.trim() == "") {
					serverResponseLabel.setText("Nome utente o password non compilati");
				} else {

					// Then, we send the input to the server.
					loginButton.setEnabled(false);
					serverResponseLabel.setText("");

					Utils.EVENT_BUS.fireEvent(new LoginEvent(username, password));
				}
			}
		}

		// Add a handler to send the name to the server
		MyHandler handler = new MyHandler();
		loginButton.addClickHandler(handler);
		userId.addKeyUpHandler(handler);
		pwd.addKeyUpHandler(handler);
	}
	
	public void onLoginError(String message) {
		DecoratedPopupPanel simplePopup = new DecoratedPopupPanel(true);
		simplePopup.ensureDebugId("cwBasicPopup-simplePopup");
		simplePopup.setWidth("150px");
		simplePopup.setTitle("Errore");
		simplePopup.setWidget(
				new HTML("Errore durante la procedura di login.\nDettaglio: " + message));
		simplePopup.show();
	}
}
